package com.jch.dm7_thread_pool.example;

import org.apache.log4j.Logger;

import java.text.DecimalFormat;
import java.util.Random;
import java.util.concurrent.*;

// 模拟 多个线程下发验证码 示例
public class SmsVerificationCodeSender {

    private static final Logger log = Logger.getLogger(SmsVerificationCodeSender.class);

    private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(), 60, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r,"VerificationSender");
            thread.setDaemon(true);
            return thread;
        }
    },new ThreadPoolExecutor.DiscardPolicy());

    public void sendVerificationSms(final String phoneNumber){
        Runnable task = new Runnable() {
            @Override
            public void run() {
                // 生成强随机数验证码
                int verificationCode = new Random().nextInt(9999);
                DecimalFormat df = new DecimalFormat("0000");
                String txtVerCode = df.format(verificationCode);
                // 发送验证码短信
                sendSms(phoneNumber,txtVerCode);
            }
        };
        EXECUTOR_SERVICE.submit(task);
    }

    private void sendSms(String phoneNumber,String verificationCode){
        log.info("Sending verification code " + verificationCode + " to " + phoneNumber);
        // 省略代码
    }

}
